package org.hhchat.leetcode.array;

import java.util.HashMap;
import java.util.Map;

/**
 * Created this one by HMH on 2017/6/12.
 * 判断是不是符合条件，看 preSum + k = sum，从小到大搜索，随时更新将Sum写为preSum
 */
public class code560 {

    public static class Solution {
        public int subarraySum(int[] nums, int k) {
            int sum=0;
            int result = 0;
            Map<Integer, Integer> preSum = new HashMap<>();
            int len = nums.length;
            preSum.put(0,1);
            for (int i = 0; i < len; i++) {
                sum+=nums[i];
                result += preSum.getOrDefault(sum - k, 0);
                preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
            }
            return result;
        }
    }
    public static void main(String[] args){
        Solution solution = new Solution();
        System.out.println(solution.subarraySum(new int[]{1,1,1,1,0},2));
    }
}
